package code

import (
	"GoNet/core"
	"fmt"
	"io"

	"code.google.com/p/goprotobuf/proto"
)

type ClientPbDecodeFilter struct {
	*core.Filter
}

func (f *ClientPbDecodeFilter) MessageRecieved(session *core.Session, obj interface{}, serverEngin *core.ServerEngin) {
	//解码
	buffer := session.InBuff

	//解析消息头
	buffer.InitReadBuf(4)

	if _, err := io.ReadFull(session.Conn, buffer.Data); err != nil {
		panic(err)
	}

	head := int(buffer.ReadUint32BE())

	fmt.Printf("头长度,%d", head)
	buffer.InitReadBuf(head)
	//解析消息体
	if _, err := io.ReadFull(session.Conn, buffer.Data); err != nil {
		panic("read message hand err")
	}

	message := new(core.Message)
	message.Type = int32(buffer.ReadUint16BE())
	message.ByteBody = buffer.Slice(head - 2)

	temp := serverEngin.HandlerBodyManager.GetBody(&message.Type)
	if temp == nil {
		panic("message Body is not exist ")
	}

	body := temp.(proto.Message)

	err := proto.Unmarshal(message.ByteBody, body)
	if err != nil {
		panic(err)
	}
	message.Session = session
	message.Body = body

	n := f.GetNext()
	if n == nil {
		return
	}
	n.MessageRecieved(session, message, serverEngin)
}
